<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 添加用户和搜索用户区域 -->
      <el-row :gutter="15">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" class="input-with-select" v-model="getUsersListParams.query" clearable @clear="getUsersList">
              <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="users" style="width: 100%;margin-top: 15px" stripe border>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="170"> </el-table-column>
        <el-table-column prop="mobile" label="电话" width="112"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" props="mg_state">
          <template slot-scope="scope">
            <!--{{ scope.row }} 表示当前这一行的数据 -->
            <!--v-model 数据双向绑定,会导致原数据跟着变化 -->
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="updataUsersMgState(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle size="small" class="operate" @click="editeMeg(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="small" class="operate" @click="deleteUserMeg(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" circle size="small" class="operate" @click="setRolesMeg(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="getUsersListParams.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="getUsersListParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="clearDialog('ruleForm')">
      <!-- 对话框主体内容 -->
      <el-form :model="ruleForm" :rules="ruleFormRules" ref="ruleForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserCheck">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑" :visible.sync="editeDialog" width="50%" @close="clearDialog('editeRuleFormRef')">
      <!-- 对话框主体内容 -->
      <el-form :model="ruleForm" :rules="ruleFormRules" ref="editeRuleFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input :disabled="true" :value="edite.currentUsername"> </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editeDialog = false">取 消</el-button>
        <el-button type="primary" @click="editeUsernameData">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="dealingRoleDialogVisible" width="50%" @close="setRightsDialogClose">
      <div>
        <p class="dealing_info">当前的用户: {{ userInfo.username }}</p>
        <p class="dealing_info">当前的角色: {{ userInfo.role_name }}</p>
        <el-select v-model="checkedRoleId" placeholder="请选择角色">
          <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dealingRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dealingNewRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import commonAPI from '@/api/commonAPI/commonAPI.js'
// 导入混入模块
import { minxin, clearDialog } from '@/mixin.js'
export default {
  mixins: [minxin, clearDialog],
  data() {
    /*
    其中
    rule: 是当前自定义规则所对应的规则对象.
    value是要验证的字段的值，cb是验证以后的回调函数
    如果值可以通过正则校验，就return cb()
    否则调用cb并且传入一个错误对象实例
    */
    const checkMobile = (rule, value, cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号码格式不正确'))
      }
    }
    return {
      // 需要被分配角色的用户信息
      userInfo: {},
      // 已选中的用户角色id
      checkedRoleId: '',
      // 角色列表
      rolesList: [],
      edite: {
        // 编辑用户的数据对象
        currentUsername: '',
        currentId: ''
      },
      getUsersListParams: {
        query: '', // 搜索关键字(''代表请求全部数据,非空将根据该值到数据库中请求到有该搜索关键字的数据)
        pagenum: 1, // 页码值
        pagesize: 2 // 数据条数
      },
      total: 0,
      users: [],
      dialogVisible: false,
      editeDialog: false,
      ruleForm: {
        username: '',
        email: '',
        password: '',
        mobile: ''
      },
      ruleFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      dealingRoleDialogVisible: false
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    // 请求用户列表数据
    async getUsersList() {
      const { data: res } = await commonAPI({ method: 'get', url: 'users', params: this.getUsersListParams })
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败')
      this.total = res.data.total
      this.users = res.data.users
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.getUsersListParams.pagesize = val
      // 改变最新的页码值后发送新的请求,拿到最新的数据
      this.getUsersList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // 把数据中的pagenum修改为最新的页数
      this.getUsersListParams.pagenum = val
      // 根据最新的页数后发送新的请求,拿到最新的数据
      this.getUsersList()
    },
    async updataUsersMgState(newUsersList) {
      // console.log(newUsersList) // 改变了用户状态的用户数据
      // 发起put请求,更新数据库中用户的数据
      const { data: res } = await commonAPI({ method: 'put', url: `users/${newUsersList.id}/state/${newUsersList.mg_state}` })
      if (res.meta.status !== 200) {
        newUsersList.mg_state = !newUsersList.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    addUserCheck() {
      // 添加用户对话框提交前进行的校验
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        // console.log(valid)
        // 发起添加用户的请求
        const { data: res } = await commonAPI({ method: 'post', url: 'users', params: this.ruleForm })
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 重新请求数据,获取最新的用户数据,渲染模板(id值后端帮生成)
        this.getUsersList()
        // 关掉对话框
        this.dialogVisible = false
      })
    },
    // 编辑用户信息
    async editeMeg(id) {
      this.editeDialog = true
      // console.log(id)
      const { data: res } = await commonAPI({ method: 'get', url: `users/${id}` })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(`请求用户id为${id}的用户数据失败!`)
      this.$message.success(`请求用户id为${id}的用户数据成功!`)
      // 得到当前用户的名字,并记录到data中
      this.edite.currentUsername = res.data.username
      this.edite.currentId = id
    },
    // 编辑用户信息
    editeUsernameData() {
      // 添加用户对话框提交前进行的校验
      this.$refs.editeRuleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await commonAPI({ method: 'put', url: `users/${this.edite.currentId}`, params: { email: this.ruleForm.email, mobile: this.ruleForm.mobile } })
        if (res.meta.status !== 200) return this.$message.error('编辑用户失败')
        this.$message.success('编辑用户成功')
        // 重新请求数据,获取最新的用户数据,渲染模板(id值后端帮生成)
        this.getUsersList()
        // 关掉对话框
        this.editeDialog = false
      })
    },
    // 删除用户信息
    async deleteUserMeg(id) {
      // console.log(id)
      const { data: res } = await commonAPI({ method: 'delete', url: `users/${id}` })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 重新请求数据,渲染模板
      this.getUsersList()
    },
    // 打开分配角色对话框
    async setRolesMeg(userInfo) {
      this.userInfo = userInfo
      // 获取角色列表
      this.getRoles()
      this.dealingRoleDialogVisible = true
    },
    // 确认为用户分配新的角色
    async dealingNewRole() {
      // 关闭对话框
      this.dealingRoleDialogVisible = false
      // 发起分配用户角色的请求
      const { data: res } = await commonAPI({ method: 'put', url: `users/${this.userInfo.id}/role`, params: { rid: this.checkedRoleId } })
      if (this.userInfo.username === 'admin') return this.$message.error('不能为超级管理员 admin 重新分配角色!')
      if (res.meta.status !== 200) return this.$message.error('分配角色失败!')
      this.$message.success(res.meta.msg)
      // 重新请求用户数据
      this.getUsersList()
    },
    // 分配角色对话框关闭时触发
    setRightsDialogClose() {
      this.userInfo = {}
      this.checkedRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.dealing_info {
  margin-bottom: 15px;
}
</style>
